using Microsoft.AspNetCore.Mvc;
using 订单API;

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    private readonly OrderService _orderService;

    public OrdersController(OrderService orderService)
    {
        _orderService = orderService;
    }

    [HttpGet]
    public ActionResult<IEnumerable<Order>> GetAllOrders()
    {
        return Ok(_orderService.GetAllOrders());
    }
    [HttpGet("{id}")]
    public ActionResult<Order> GetOrder(string id)
    {
        var orders = _orderService.QueryByOrderId(id);
        if (orders.Count == 0) return NotFound();
        return Ok(orders.First());
    }

    [HttpPost]
    public ActionResult<Order> CreateOrder([FromBody] Order order)
    {
        _orderService.Add(order);
        return CreatedAtAction(nameof(GetOrder), new { id = order.OrderId }, order);
    }

    [HttpDelete("{id}")]
    public IActionResult DeleteOrder(string id)
    {
        try
        {
            _orderService.Remove(id);
            return NoContent();
        }
        catch (ArgumentException ex)
        {
            return NotFound(ex.Message);
        }
    }

    [HttpPost("{id}/details")]
    public IActionResult AddOrderDetail(string id, [FromBody] Orderdetail detail)
    {
        try
        {
            _orderService.AddOrderDetail(id, detail);
            return Ok();
        }
        catch (ArgumentException ex)
        {
            return BadRequest(ex.Message);
        }
    }


    [HttpGet("search")]
    public ActionResult<IEnumerable<Order>> SearchOrders(
        [FromQuery] string orderId = null,
        [FromQuery] string productName = null,
        [FromQuery] string customerName = null)
    {
        if (!string.IsNullOrEmpty(orderId))
        {
            return Ok(_orderService.QueryByOrderId(orderId));
        }
        else if (!string.IsNullOrEmpty(productName))
        {
            return Ok(_orderService.QueryByProductName(productName));
        }
        else if (!string.IsNullOrEmpty(customerName))
        {
            return Ok(_orderService.QueryByCustomer(customerName));
        }
        return BadRequest("请提供查询条件");
    }
}